Skip to main content

Hello World!

Try PowerShell - Let's do it!

There are a lot of resources out there that teach you how to write or code PowerShell script. However, in this series let's learn it as a programming language instead of as learning the commands and just what they do. This will prepare you to be a better PowerShell Tool maker in the future if you pursuit it.

Let's begin with the Hello World script. The simplest way to print Hello World on the screen is to just type in "Hello World!" with either single or double quotes around it. Once you press 'Enter', you will get the Hello World! message on the next line.

Well, That's it. You've done your first Hello World PowerShell script. But let's not stop there instead let's break it down what has happened. If you type in just hello world without the single or double quote on the console, it will throw an error.

Remember this: Unlike Bash script where the ouputs are just plain text, PowerShell outputs are Objects. The pipline inputs and outputs are also objects.

If you try the command below, it will tell you the output you are getting is 'String' and the base type is 'System.Object'

"Hello World!".GetType()

Let's explore a bit further with more cmdlets.

HelloWorld.ps1
#Print Hello World! on the PowerShell Console.
Write-Host 'Hello World!'
'Hello World!' | Out-Host

#Display Hello World! on the Console. This can be an input object to a pipeline.
Write-Output 'Hello World!'

#Give you a Warning Hello World! on the console.
Write-Warning 'Hellow World!'

#Write error message on the console. The script will continue to run.
Write-Error 'Hello World!'

#Write debugging message on the console.
Write-Debug 'Hello World!' -Debug

#Create verbose message and display it on the console.
Write-Verbose 'Hello World!' -Verbose

#Give you an information message on the console
Write-Information 'Hello World!' -InformationAction Continue

To reuse - save your powershell script file with the extension ps1 (HelloWorld.ps1) and run it on the console by using .\HelloWorld.ps1

#This will throw an exception and the script will halt.
Throw 'Hello World!'

#Write-Host vs Write-Output
Write-Host 'Hello World!' | Measure-Object
Write-Output 'Hello World!' | Measure-Object

Run the cmdlets above and you will see that Write-Host prints the Hello World! on the screen and returns the object count as 0 whereas Write-Output doesn't print the Hello World! but returns the object count as 1.

Take away

Be mindful of what you are trying to achieve. Choose the right cmdlet for the right behaviour when you are writing your script. Sometimes, different PowerShell version also produces different behaviour for the same cmdlet.